﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using com.codebump;

public partial class OperationSmile_OperationSmile : System.Web.UI.Page
{
    string _EmailServer;
    string _LoginName;
    string _LoginPassword;
    string _FromEmail;
    string _FromName;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString.HasKeys())
            {
                if (Request.QueryString["listid"] != String.Empty)
                    Session["listid"] = Request.QueryString["listid"];
                else
                    Session["listid"] = 1;


                if (Request.QueryString["dnis"] != null)
                {
                    Session["dnis"] = Request.QueryString["dnis"];
                }
                else
                {
                    Session["dnis"] = "9999999999";
                }

                Session["servername"] = Request.QueryString["servername"];
                Session["projectname"] = Request.QueryString["projectname"];
                Session["campaignname"] = Request.QueryString["campaignname"];
                Session["agentid"] = Request.QueryString["agentid"];
                Session["agentfirst"] = Request.QueryString["agentfirst"];
                Session["agentlast"] = Request.QueryString["agentlast"];
                Session["commit"] = false;
                Session["App"] = new DataAccess();


                //ValidateIBListID();
            }
            //The session variables are requested in the master page currently using the following syntax: Session["servername"] = Request.QueryString["servername"];
            //The page is loaded before the master page so if the code isn't in a control, it will currently error out.
            //((DataAccess)Session["App"]).ConnectInbound(Session["servername"].ToString(), Session["projectname"].ToString(), Session["campaignname"].ToString(), Session["dnis"].ToString(), Session["listid"].ToString());
            prepopulateFields();
            WebWizard.ActiveStepIndex = 0;
            Session["CInfo"] = false;
            ((DataAccess)Session["App"]).PutCallData("ModifiedDate", string.Format("{0:yyyy/MM/dd}", System.DateTime.Today));
            ((DataAccess)Session["App"]).CommitCallData();
        }
        else
        {

        }


    }
    //POST LOGIC - For Step or Start pages
    //Add if statements as you add pages
    //For Next and Finish pages it is best to use the index in the if statements as below
    protected void WebWizard_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        int page = WebWizard.ActiveStepIndex;
        if (page == WebWizard.WizardSteps.IndexOf(this.Introduction))
        {
            return;
        }

        if (page == WebWizard.WizardSteps.IndexOf(this.MonthlyDonation))
        {
           
            tbOpenOneTime.Text = "0.00";
            tbOpenOneTime_TextChanged(null, null);
            //see what page we go to
            if (cbMonthlyTwentyOne.Checked)
            {
                if (cbOneTimeToo.Checked)
                {
                    //go to one-time pmt
                    lblMonthlyPlusOne.Text = " plus a monthly payment of $" + lblMonthlyDonation.Text;
                    tbOpenOneTime_TextChanged(null, null);
                }
                else
                {
                    //jump to collect info
                    WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.GatherInfo);
                }

            }
            else if (Convert.ToDouble(tbOpenMonthlyDonation.Text) > 0.0)
            {
                if (cbOneTimeToo.Checked)
                {
                    //go to one-time pmt
                    lblMonthlyPlusOne.Text = " plus a monthly payment of $" + lblMonthlyDonation.Text;
                    tbOpenOneTime_TextChanged(null, null);
                }
                else
                {
                    //jump to collect info
                    WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.GatherInfo);
                }
            }
            else
            {
                cbOneTimeToo.Checked = false;
                lblMonthlyPlusOne.Text = "";
                tbOpenOneTime_TextChanged(null, null);
                //go to one-time pmt
            }
            return;
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.OneTimeGift)) 
        {
            

            //see what page we go to
            if (Convert.ToDouble(tbOpenOneTime.Text) > 0.0)
            {
                //if we have a one-time donation. 
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.GatherInfo);
            }
            else if (cbMonthlyTwentyOne.Checked || Convert.ToDouble(tbOpenMonthlyDonation.Text) > 0.0)
            {
                //if previous payment is there, but for whatever reason they got to this page and changed their mind on the one-time donation
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.GatherInfo);
            }
            else
            {
                //go to brochure page
            }
            return;

        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Brochure))
        {
            switch(ddlBrochureRebuttal.SelectedIndex)
            {
                case 0:
                    pnlCCInfo.Visible = false;
                    pnlMailDonation.Visible = false;
                    ddlPaymentType.SelectedIndex = 3; //index of no payment
                    ddlPaymentType.Enabled = false;
                    ddlPaymentType_SelectedIndexChanged(null, null);
                    break;
                case 1:
                    WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.OneTimeGift);
                    break;
                case 2:
                    WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.MonthlyDonation);
                    break;
            }
            return;
        }
        //if (page == WebWizard.WizardSteps.IndexOf(this.Disposition))
        //{
        //    return;
        //}
    }

    //POST LOGIC for disposition pages
    //this is for pages that contain a disposition button
    protected void WebWizard_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {

        int page = WebWizard.ActiveStepIndex;
        //if (page == WebWizard.WizardSteps.IndexOf(this.Intro))
        //{
        //    return;
        //}
        if (page == WebWizard.WizardSteps.IndexOf(this.Recap))
        {

            return;
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Disposition))
        {
            return;
        }


    }

    //PRE-LOGIC
    //Add if statements as needed for post-logic
    //You can use the Step ID name instead of the index as used in Next and Finish logic.
    protected void WebWizard_ActiveStepChanged(object sender, EventArgs e)
    {
        int page = WebWizard.ActiveStepIndex;

        if(page== WebWizard.WizardSteps.IndexOf(this.MonthlyDonation))
        {
            lblAmountError.Text = ""; //clear amt error (all things that write it set it to 0.00)

            if (ddlPaymentType.SelectedIndex == 3)
            {
                ddlPaymentType.SelectedIndex = 0;
                ddlPaymentType_SelectedIndexChanged(null, null);
            }
            ddlPaymentType.Enabled = true;
        }
        if(page == WebWizard.WizardSteps.IndexOf(this.OneTimeGift))
        {
            lblAmountError.Text = ""; //clear amt error (all things that write it set it to 0.00)

            if (ddlPaymentType.SelectedIndex == 3)
            {
                ddlPaymentType.SelectedIndex = 0;
                ddlPaymentType_SelectedIndexChanged(null, null);
            }
            ddlPaymentType.Enabled = true;
        }
        if(page == WebWizard.WizardSteps.IndexOf(this.GatherInfo))
        {
            ddlPaymentType_SelectedIndexChanged(null, null);

            //if there is a one-time payment, supercede monthly
            //fill auth amount label
            if (Convert.ToDouble(lblTotalOneTime.Text) > 0.0)
            {
                lblAuthAmt.Text = lblTotalOneTime.Text;
            }
            else
            {
                lblAuthAmt.Text = lblMonthlyDonation.Text;
            }
            return;
        }
        if (WebWizard.ActiveStep.Title.ToString() == "Recap")
        {
            //RecapText();
            btnSubmit_Click(null, null);    //just in case they change card and forget to re-submit or something like that.

            if(ddlPaymentType.SelectedIndex == 1 && lblTransactionID.Text == "")//(lblAuthCode.Text == "" || lblAuthCode.Text == "declined"))
            {
                lblError.Text += "<br/>Please auth a valid CC or change the pay method.";
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.GatherInfo);
                return;
            }

            if ((bool)Session["CInfo"])
            {
                RecapText(false);
            }
            else
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.GatherInfo);
            }

            //lblTest1.Text = ((DataAccess)Session["App"]).GetCallData("UpFrontAmount").ToString();
            //lblTest2.Text = ((DataAccess)Session["App"]).GetCallData("RecurringAmount").ToString();
            //lblTest3.Text = ((DataAccess)Session["App"]).GetCallData("RecurringPaymentDay").ToString();
            return;
        }
        if (WebWizard.ActiveStep.Title.ToString() == "Disposition")
        {

            if ((bool)Session["CInfo"])
            {

                pnlDispoConfirm.Visible = false;
                if(!string.IsNullOrEmpty(tbNotes.Text))
                {
                    ((DataAccess)Session["App"]).PutCallData("notes", tbNotes.Text);
                }
                if (ddlPaymentType.SelectedIndex == 1 && cbTShirt.Checked)
                {
                    ((DataAccess)Session["App"]).PutCallData("TShirt", "Y");
                }
                else
                {

                    ((DataAccess)Session["App"]).PutCallData("TShirt", "");
                }
                ((DataAccess)Session["App"]).PutCallData("SurveyResult", ddlSurvey.SelectedItem.Text);
                if (ddlSurvey.SelectedItem.Text == "Other")
                {
                    ((DataAccess)Session["App"]).PutCallData("OtherSurvey", tbSurveyOther.Text);
                }
                else
                {
                    ((DataAccess)Session["App"]).PutCallData("OtherSurvey", "");    //put this in in case they are somehow able to do this more than once with a different value.
                }
                RecapText(true);
                SendEmail();
                ((DataAccess)Session["App"]).CommitCallData();
                Response.Redirect("../DispositionComplete.aspx");
            }
            else
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Recap);
            }
            return;
        }
        else
        {
        }

    }


    ///***************************
    protected void ddlPaymentType_SelectedIndexChanged(object sender, EventArgs e)
    {
        RecapText(false);
        Session["CInfo"] = false;
        pnlCCInfo.Visible = false;
        pnlMailDonation.Visible = false;
        switch (ddlPaymentType.SelectedIndex)
        {
            case 0: //blank
                break;
            case 1: //credit
                trCCNumber.Visible = true;
                trCCType.Visible = true;
                trCCExpDate.Visible = true;
                trCCV.Visible = true;
                trECAccNum.Visible = false;
                trECBankName.Visible = false;
                trECRoutNum.Visible = false;
                trECAccType.Visible = false;
                trECAccHolder.Visible = false;
                tbAccHolder.Text = "";
                tbAccNum.Text = "";
                tbBankName.Text = "";
                tbRoutNum.Text = "";

                pnlCCInfo.Visible = true;
                break;
            case 2: //Mail In
                trCCNumber.Visible = false;
                trCCType.Visible = false;
                trCCExpDate.Visible = false;
                trCCV.Visible = false;
                trECAccNum.Visible = false;
                trECBankName.Visible = false;
                trECRoutNum.Visible = false;
                trECAccType.Visible = false;
                trECAccHolder.Visible = false;
                tbCCNumber.Text = "";
                tbExpDate.Text = "";
                tbAccHolder.Text = "";
                tbAccNum.Text = "";
                tbBankName.Text = "";
                tbRoutNum.Text = "";

                pnlMailDonation.Visible = true;
                break;
            case 3: //No payment
                trCCNumber.Visible = false;
                trCCType.Visible = false;
                trCCExpDate.Visible = false;
                trCCV.Visible = false;
                trECAccNum.Visible = false;
                trECBankName.Visible = false;
                trECRoutNum.Visible = false;
                trECAccType.Visible = false;
                trECAccHolder.Visible = false;
                tbCCNumber.Text = "";
                tbExpDate.Text = "";
                tbAccHolder.Text = "";
                tbAccNum.Text = "";
                tbBankName.Text = "";
                tbRoutNum.Text = "";
                break;
        }

        if ((cbMonthlyTwentyOne.Checked || Convert.ToDouble(tbOpenMonthlyDonation.Text) >= 18.0 || Convert.ToDouble(tbOpenOneTime.Text) >= 240.0) && ddlPaymentType.SelectedIndex == 1)
        {
            spanTshirt.Visible = true;
        }
        else
        {
            spanTshirt.Visible = false;
        }
        

    }

    protected void cbShipping_CheckedChanged(object sender, EventArgs e)
    {
        if (cbShipping.Checked)
        {

            trShipAddr.Visible = true;
            trShipAddr2.Visible = true;
            trShipCity.Visible = true;
            trShipState.Visible = true;
            trShipCountry.Visible = true;
            trShipZip.Visible = true;
            trShipLbl.Visible = true;
            trShipSearchZip.Visible = true;

        }
        else
        {
            trShipAddr.Visible = false;
            trShipAddr2.Visible = false;
            trShipCity.Visible = false;
            trShipState.Visible = false;
            trShipCountry.Visible = false;
            trShipZip.Visible = false;
            trShipLbl.Visible = false;
            trShipSearchZip.Visible = false;
        }
    }

    protected void btnSearchZip_Click(object sender, EventArgs e)
    {
        ValidateZip(tbZip.Text.ToUpper(), ddlCity, ddlState, ddlCountry);
        //if (cbShipping.Checked)
        //{
        //    if (ddlShipCountry.SelectedItem.Text == "CANADA")
        //    {
        //        ddlPaymentType.Items[2].Enabled = false;
        //    }
        //}
        //else if (ddlCountry.SelectedItem.Text == "CANADA")
        //{
        //    ddlPaymentType.Items[2].Enabled = false;
        //}
        //else
        //{
        //    ddlPaymentType.Items[2].Enabled = true;
        //}
    }

    protected void btnShipSearchZip_Click(object sender, EventArgs e)
    {
        ValidateZip(tbShipZip.Text.ToUpper(), ddlShipCity, ddlShipState, ddlShipCountry);
        //if (cbShipping.Checked)
        //{
        //    if (ddlShipCountry.SelectedItem.Text == "CANADA")
        //    {
        //        ddlPaymentType.Items[2].Enabled = false;
        //    }
        //    else
        //    {
        //        ddlPaymentType.Items[2].Enabled = true;
        //    }
        //}
    }

    protected void ValidateZip(string strZip, DropDownList ddl_City, DropDownList ddl_State, DropDownList ddl_Country)
    {

        ddl_City.Items.Clear();
        ddl_State.Items.Clear();
        ddl_City.Enabled = true;
        ddl_State.Enabled = true;
        if (System.Text.RegularExpressions.Regex.IsMatch(strZip.ToUpper(), @"(^\d{5}$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} +\d{1}[A-Z]{1}\d{1}$)"))
        {
            try
            {
                com.codebump.GeoPlaces g = new com.codebump.GeoPlaces();

                com.codebump.AuthenticationHeader authHeader = new com.codebump.AuthenticationHeader();
                authHeader.SessionID = "6JV2ZA4lgG1YRR+HG+JU27QWk9zI3rpRWY2iG2mzNPcdieEQXfQv0OUY0EZ+pOTxhwI1NCuF7b2oY+U/bozy0mhjFHmpaXvb";
                g.AuthenticationHeaderValue = authHeader;

                com.codebump.GeoPlaceDistance[] places = g.GetPlacesInside(strZip, "");

                for (int i = 0; i < places.Length; i++)
                {
                    com.codebump.GeoPlaceDistance place = places[i];
                    ListItem li = new ListItem(place.ToPlace, place.ToState + "," + place.ToPlace);
                    ddl_City.Items.Add(li);
                }

                ddl_State.Items.Add(ddl_City.SelectedItem.Value.Split(",".ToCharArray())[0]);
                
                //ddlCity.SelectedIndex = 0;

                if (System.Text.RegularExpressions.Regex.IsMatch(strZip.ToUpper(), @"(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)"))
                {
                    ddl_Country.SelectedValue = "CANADA";
                }
                else
                {
                    ddl_Country.SelectedValue = "USA";
                }

                if (ddl_City.Items.Count <= 0)
                {
                    ddl_City.Items.Add("No Cities Found");
                    ddl_State.Items.Add("No States Found");
                    ddl_City.Enabled = false;
                    ddl_State.Enabled = false;
                }
                else
                {
                    ddl_City.Items.Insert(0, "Select a City");
                    ddl_City.SelectedIndex = 0;
                    ddl_State.Enabled = false;
                }
            }
            catch
            {
                ddl_City.Items.Add("No Cities Found");
                ddl_State.Items.Add("No States Found");
                ddl_City.Enabled = false;
                ddl_State.Enabled = false;
            }
        }
        else
        {
            ddl_City.Items.Add("Invalid Zip");
            ddl_City.Enabled = false;
            ddl_State.Items.Add("Invalid Zip");
            ddl_State.Enabled = false;
        }
    }

    public DataAccess.CardType GetCardType(string cardType)
    {
        switch (cardType)
        {
            case "A":
                return DataAccess.CardType.AmericanExpress;
            case "V":
                return DataAccess.CardType.Visa;
            case "D":
                return DataAccess.CardType.Discover;
            case "M":
                return DataAccess.CardType.MasterCard;
            default:
                return DataAccess.CardType.Visa;
        }
    }

    public double GetOrderTotalPerItemShipping()
    {
        double BaseTotal = 0.00;
        double ShippingTotal = 0.00;
        for (int i = 0; i < (((DataAccess)Session["App"]).GetOrder()).Rows.Count; i++)
        {
            BaseTotal += Convert.ToDouble((Convert.ToDouble((((DataAccess)Session["App"]).GetOrder()).Rows[i]["BaseRevenue"])) * Convert.ToDouble((((DataAccess)Session["App"]).GetOrder()).Rows[i]["Quantity"]));
            ShippingTotal = ShippingTotal + Convert.ToDouble((Convert.ToDouble((((DataAccess)Session["App"]).GetOrder()).Rows[i]["SecondaryRevenue"])) * Convert.ToDouble((((DataAccess)Session["App"]).GetOrder()).Rows[i]["Quantity"]));
        }

        if (cbShipping.Checked)
        {
            if (ddlShipState.Items.Count > 0)   //error checking to make sure there is a state
            {
                if (ddlShipState.SelectedItem.Text == "IL")
                {
                    BaseTotal *= 1.07;
                }
            }
        }
        else
        {
            if (ddlState.Items.Count > 0)//error checking to make sure there is a state
            {
                if (ddlState.SelectedItem.Text == "IL")
                {
                    BaseTotal *= 1.07;
                }
            }
        }
        return Math.Round((BaseTotal + ShippingTotal), 2);
    }
    public double GetRecurringPayment()
    {
        double secTotal = 0.00;
        DataTable productscomp = new DataTable();
        for (int i = 0; i < (((DataAccess)Session["App"]).GetOrder()).Rows.Count; i++)
        {

            //productscomp = ((DataAccess)Session["App"]).GetProducts("ProductID = " + ((DataAccess)Session["App"]).GetOrder().Rows[i]["ProductID"].ToString());
            productscomp = ((DataAccess)Session["App"]).GetProducts("ProductID", ((DataAccess)Session["App"]).GetOrder().Rows[i]["ProductID"].ToString());
            if (productscomp.Rows[0]["Group2"].ToString() == "3-pay")
            {
                secTotal += Convert.ToDouble(Convert.ToDouble(((DataAccess)Session["App"]).GetOrder().Rows[i]["BaseRevenue"]) * Convert.ToDouble(((DataAccess)Session["App"]).GetOrder().Rows[i]["Quantity"]));
            }

        }

        if (cbShipping.Checked)
        {
            if (ddlShipState.Items.Count > 0) //error checking to make sure there is a state
            {
                if (ddlShipState.SelectedItem.Text == "IL")
                {
                    secTotal *= 1.07;
                }
            }
        }
        else
        {
            if (ddlState.Items.Count > 0) //error checking to make sure there is a state
            {
                if (ddlState.SelectedItem.Text == "IL")
                {
                    secTotal *= 1.07;
                }
            }
        }
        return Math.Round(secTotal, 2);
    }


    
    #region Validate customer info and write it to in-memory calldata table

    protected void btnSubmit_Click(object sender, System.EventArgs e)
    {
        lblError.Text = "";
        bool bCustValid = validateCustomer();
        bool bShipValid = validateShipping();
        bool bPmtValid = validatePayment();

        if (bCustValid) //If required data is valid, check if optional data is valid. If not, set bCustValid to invalid
        {
            bCustValid = submitOptionalData();
        }
        submitCustData(bCustValid, bShipValid);
        submitPmtInfo(bPmtValid);

        if (bCustValid && (bPmtValid))
        {
            if (!cbShipping.Checked || bShipValid)
            {
                Session["CInfo"] = true;
            }
            else
            {
                Session["CInfo"] = false;
            }
        }
        else
        {
            Session["CInfo"] = false;
        }

        ((DataAccess)Session["App"]).CommitCallData();
    }
    protected bool validateCustomer()
    {
        bool bCustValid = false;

        bCustValid = !(ddlTitle.SelectedIndex == 0 || 
            string.IsNullOrEmpty(tbFirstName.Text) ||
            string.IsNullOrEmpty(tbLastName.Text) ||
            string.IsNullOrEmpty(tbAddr.Text) ||
            (tbAddr.Text == "PO BOX ") ||
            string.IsNullOrEmpty(tbZip.Text) ||
            string.IsNullOrEmpty(ddlCity.SelectedItem.Text) ||
            string.IsNullOrEmpty(ddlState.SelectedItem.Text) ||
            string.IsNullOrEmpty(ddlCountry.SelectedItem.Text)) &&
            (ddlCity.SelectedIndex > 0);

        return bCustValid;
    }
    protected bool validateShipping()
    {
        bool bShipValid = false;

        bShipValid = !(string.IsNullOrEmpty(tbShipAddr.Text) ||
           (tbShipAddr.Text == "PO BOX ") ||
            //string.IsNullOrEmpty(tbShipaddr2.Text) ||
           string.IsNullOrEmpty(tbShipZip.Text) ||
           string.IsNullOrEmpty(ddlShipCity.SelectedItem.Text) ||
           ddlShipState.Items.Count <= 0 ||
           string.IsNullOrEmpty(ddlShipState.SelectedItem.Text) ||
           string.IsNullOrEmpty(ddlShipCountry.SelectedItem.Text)) &&
           (ddlShipCity.SelectedIndex > 0) &&
           (tbShipZip.Text.Length >= 5) &&
           (tbShipZip.Text.Length <= 7);

        return bShipValid;
    }
    protected bool validatePayment()
    {
        bool pmtCheck = false;
        int yearval = Convert.ToInt32(DateTime.Today.ToString("yy"));
        switch (ddlPaymentType.SelectedIndex)
        {
            case 1: //CC or Debit card
                pmtCheck = !(string.IsNullOrEmpty(ddlCardType.SelectedItem.Text) ||
                    string.IsNullOrEmpty(tbCCNumber.Text) ||
                    string.IsNullOrEmpty(tbCCV.Text) ||
                    string.IsNullOrEmpty(tbExpDate.Text) ||
                    (Convert.ToInt32(tbExpDate.Text.Substring(2, 2)) == yearval && Convert.ToInt32(tbExpDate.Text.Substring(0, 2)) < Convert.ToInt32(DateTime.Today.ToString("MM")))) &&
                    (Convert.ToInt32(tbExpDate.Text.Substring(2, 2)) >= yearval) &&
                    (Convert.ToInt32(tbExpDate.Text.Substring(2, 2)) <= (yearval + 10)) &&
                    (Convert.ToInt32(tbExpDate.Text.Substring(0, 2)) >= 1 && Convert.ToInt32(tbExpDate.Text.Substring(0, 2)) <= 12) &&
                    (((DataAccess)Session["App"]).IsValidCC(GetCardType(ddlCardType.SelectedValue), tbCCNumber.Text)) &&
                    tbExpDate.Text.Length == 4 &&
                    (System.Text.RegularExpressions.Regex.IsMatch(tbExpDate.Text, @"^[\d]+$"));
                break;
            //case 2: //EFT
            //    pmtCheck = !(string.IsNullOrEmpty(tbBankName.Text) ||
            //        string.IsNullOrEmpty(tbAccHolder.Text) ||
            //        string.IsNullOrEmpty(tbAccNum.Text) ||
            //        string.IsNullOrEmpty(tbRoutNum.Text)) &&
            //        (System.Text.RegularExpressions.Regex.IsMatch(tbAccNum.Text, @"^[\d]+$")) &&
            //        (System.Text.RegularExpressions.Regex.IsMatch(tbRoutNum.Text, @"^[\d]+$")) &&
            //        ((DataAccess)Session["App"]).ValidateRoutingNumber(Convert.ToInt32(tbRoutNum.Text));
            //    break;
            case 2: //Mail in. No additional pmt info to gather
                pmtCheck = true;
                break;
            case 3:
                pmtCheck = true;
                break;
            default:
                pmtCheck = false;
                lblError.Text += "Please select a payment method<br/>";
                break;

        }
        return pmtCheck;

    }
    protected void submitCustData(bool bCustValid, bool bShipValid)
    {
        if (bCustValid)
        {
            ((DataAccess)Session["App"]).PutCallData("Title", ddlTitle.SelectedItem.Text);
            ((DataAccess)Session["App"]).PutCallData("firstname", tbFirstName.Text.Replace(",", ""));
            ((DataAccess)Session["App"]).PutCallData("lastname", tbLastName.Text.Replace(",", ""));
            ((DataAccess)Session["App"]).PutCallData("Address", tbAddr.Text.Replace(",", ""));
            if (!string.IsNullOrEmpty(tbAddr2.Text))
                ((DataAccess)Session["App"]).PutCallData("Address2", tbAddr2.Text.Replace(",", ""));
            else
                ((DataAccess)Session["App"]).PutCallData("Address2", "");
            ((DataAccess)Session["App"]).PutCallData("Zip", tbZip.Text.Replace(",", ""));
            ((DataAccess)Session["App"]).PutCallData("City", ddlCity.SelectedItem.Text.Replace(",", ""));
            ((DataAccess)Session["App"]).PutCallData("State", ddlState.SelectedItem.Text);
            ((DataAccess)Session["App"]).PutCallData("Country", ddlCountry.SelectedItem.Text);

            //this is what happens if the shipping info is not visible
            if (!cbShipping.Checked)
            {
                ((DataAccess)Session["App"]).PutCallData("ShippingAddress", tbAddr.Text.Replace(",", ""));
                if (!string.IsNullOrEmpty(tbAddr2.Text))
                    ((DataAccess)Session["App"]).PutCallData("ShippingAddress2", tbAddr2.Text.Replace(",", ""));
                else
                    ((DataAccess)Session["App"]).PutCallData("ShippingAddress2", "");
                ((DataAccess)Session["App"]).PutCallData("ShippingZip", tbZip.Text.Replace(",", ""));
                ((DataAccess)Session["App"]).PutCallData("ShippingCity", ddlCity.SelectedItem.Text.Replace(",", ""));
                ((DataAccess)Session["App"]).PutCallData("ShippingState", ddlState.SelectedItem.Text);
                ((DataAccess)Session["App"]).PutCallData("ShippingCountry", ddlCountry.SelectedItem.Text);
            }
            //this is what happens if the shipping info is visible
            else
            {
                if (bShipValid)
                {
                    ((DataAccess)Session["App"]).PutCallData("ShippingAddress", tbShipAddr.Text.Replace(",", ""));
                    if (!string.IsNullOrEmpty(tbShipAddr.Text))
                        ((DataAccess)Session["App"]).PutCallData("ShippingAddress2", tbShipaddr2.Text.Replace(",", ""));
                    else
                        ((DataAccess)Session["App"]).PutCallData("ShippingAddress2", "");
                    ((DataAccess)Session["App"]).PutCallData("ShippingZip", tbShipZip.Text.Replace(",", ""));
                    ((DataAccess)Session["App"]).PutCallData("ShippingCity", ddlShipCity.SelectedItem.Text.Replace(",", ""));
                    ((DataAccess)Session["App"]).PutCallData("ShippingState", ddlShipState.SelectedItem.Text);
                    ((DataAccess)Session["App"]).PutCallData("ShippingCountry", ddlShipCountry.SelectedItem.Text);
                }
                else
                {
                    lblError.Text += "Enter Valid Shipping Info<br/>";
                }
            }
        }
        //this else covers error checking
        else
        {
            if (tbAddr.Text == "PO BOX ")
            {
                lblError.Text += "Enter a PO BOX number <br/>";
            }
            else
            {
                if (ddlCity.Items.Count > 1 && ddlCity.SelectedIndex == 0)
                {
                    lblError.Text += "Select a City<br/>";
                }
                else
                {
                    lblError.Text += "Enter Valid Customer Data<br/>";
                }
            }
        }

    }
    protected bool submitOptionalData()
    {
        bool bOpt = true;

        if ((!string.IsNullOrEmpty(tbPhone.Text)) && ((tbPhone.Text.Length != 10) || !(System.Text.RegularExpressions.Regex.Match(tbPhone.Text, @"^[1-9]\d{2}[1-9]\d{6}$").Success)))
        {
            lblError.Text += "Invalid Phone<br/>";
            bOpt = false;
        }
        else
        {
            if (!string.IsNullOrEmpty(tbPhone.Text))
                ((DataAccess)Session["App"]).PutCallData("Phone", tbPhone.Text);
        }

        if ((!string.IsNullOrEmpty(tbEmail.Text)) && !((DataAccess)Session["App"]).IsValidEmail(tbEmail.Text))
        {
            lblError.Text += "Invalid Email<br/>";
            bOpt = false;
        }
        else
        {
            if (!string.IsNullOrEmpty(tbEmail.Text))
                ((DataAccess)Session["App"]).PutCallData("Email", tbEmail.Text);
        }

        return bOpt;
    }
    protected void submitPmtInfo(bool bPmtValid)
    {
        if (bPmtValid)
        {
            ((DataAccess)Session["App"]).PutCallData("PaymentType", ddlPaymentType.SelectedItem.Value);

            switch (ddlPaymentType.SelectedIndex)
            {
                case 1: //Credit Card
                    ((DataAccess)Session["App"]).PutCallData("CCType", ddlCardType.SelectedItem.Value);
                    ((DataAccess)Session["App"]).PutCallData("CCNumber", ((DataAccess)Session["App"]).EnryptData(tbCCNumber.Text));
                    //((DataAccess)Session["App"]).PutCallData("CCV", ((DataAccess)Session["App"]).EnryptData(tbCCV.Text));
                    ((DataAccess)Session["App"]).PutCallData("CCExpDate", ((DataAccess)Session["App"]).EnryptData((tbExpDate.Text.Substring(0, 2) + "/" + tbExpDate.Text.Substring(2, 2))));
                    break;
                //case 2: //E-Check
                //    ((DataAccess)Session["App"]).PutCallData("ECBankName", tbBankName.Text.Replace(",", ""));
                //    ((DataAccess)Session["App"]).PutCallData("ECAccHolder", tbAccHolder.Text.Replace(",", ""));
                //    ((DataAccess)Session["App"]).PutCallData("ECAccNumber", tbAccNum.Text);
                //    ((DataAccess)Session["App"]).PutCallData("ECRoutingNumber", tbRoutNum.Text);
                //    ((DataAccess)Session["App"]).PutCallData("ECAccType", ddlAccType.SelectedItem.Text);
                //    break;
            }
        }
        else
        {
            lblError.Text += "Invalid Payment Info<br/>";
        }
    }
    #endregion Validate customer info and write it to in-memory calldata table
    protected void tbOpenOneTime_TextChanged(object sender, EventArgs e)
    {
        //return;
        if (System.Text.RegularExpressions.Regex.IsMatch(tbOpenOneTime.Text, @"^\d{1,5}(\.\d{1,2})?$"))
        {
            double total = Convert.ToDouble(tbOpenOneTime.Text);
            string upgradeAmt = "";

            cbOneTimeUpgrade.Text = "Increase gift amount by $"; //reset text on checkbox

            pnlOneTimeUpgrade.Visible = true;   //make the upgrade ask visible.

            if (total > 150.0)
            {
                upgradeAmt = "20";
            }
            else if (total > 100.0)
            {
                upgradeAmt = "15";
            }
            else if (total > 50.0)
            {
                upgradeAmt = "10";
            }
            else
            {
                upgradeAmt = "5";
            }

            lblUpgradeAmt.Text = upgradeAmt;
            cbOneTimeUpgrade.Text += upgradeAmt;

            cbOneTimeUpgrade_CheckedChanged(null, null);    //added in case they want to change their donation after deciding to increase by upgrade amount

            lblAmountError.Text = "";
        }
        else
        {
            //They don't have a valid amount in the upgrade field
            lblTotalOneTime.Text = "0.00";
            tbOpenOneTime.Text = "0.00";
            lblAmountError.Text = "Please enter a valid dollar amount in the format XXX.XX before continuing";
        }
        if (Convert.ToDouble(tbOpenOneTime.Text) > 0)
        {
        }
        else
        {
            pnlOneTimeUpgrade.Visible = false;
            cbOneTimeUpgrade.Checked = false;
        }
    }
    protected void cbOneTimeUpgrade_CheckedChanged(object sender, EventArgs e)
    {
        if (cbOneTimeUpgrade.Checked)
        {
            //if (cbOneTimeToo.Checked)
            //{
            //    lblTotalOneTime.Text = (Convert.ToDouble(tbOpenOneTime.Text) + Convert.ToDouble(lblUpgradeAmt.Text) + Convert.ToDouble(lblMonthlyDonation.Text)).ToString();  //add amounts together
            //}
            //else
            //{
                lblTotalOneTime.Text = (Convert.ToDouble(tbOpenOneTime.Text) + Convert.ToDouble(lblUpgradeAmt.Text)).ToString();  //add amounts together
            //}
        }
        else
        {
            //if (cbOneTimeToo.Checked)
            //{
            //    lblTotalOneTime.Text = (Convert.ToDouble(tbOpenOneTime.Text) + Convert.ToDouble(lblMonthlyDonation.Text)).ToString();  //add amounts together
            //}
            //else
            //{
                lblTotalOneTime.Text = tbOpenOneTime.Text;
            //}
        }
        
    }
    protected void cbMonthlyTwentyOne_CheckedChanged(object sender, EventArgs e)
    {
        if (!cbMonthlyTwentyOne.Checked)
        {
            pnlOpenMonthlyDonation.Visible = true;
            lblMonthlyDonation.Text = tbOpenMonthlyDonation.Text;
        }
        else
        {
            pnlOpenMonthlyDonation.Visible = false;
            tbOpenMonthlyDonation.Text = "0.00";
            lblAmountError.Text = "";
            lblMonthlyDonation.Text = "21.00";
        }
    }
    protected void tbOpenMonthlyDonation_TextChanged(object sender, EventArgs e)
    {

        if (System.Text.RegularExpressions.Regex.IsMatch(tbOpenMonthlyDonation.Text, @"^\d{1,5}(\.\d{1,2})?$"))
        {
            lblAmountError.Text = "";
        }
        else
        {
            tbOpenMonthlyDonation.Text = "0.00";
            lblAmountError.Text = "Please enter a valid dollar amount in the format XXX.XX before continuing"; 
        }
        lblMonthlyDonation.Text = tbOpenMonthlyDonation.Text;
        
    }
    protected void RecapText(bool dispo)
    {
        pnlBadCCMonthly.Visible = false;
        pnlBadCCOneTime.Visible = false;
        pnlCCMonthly.Visible = false;
        pnlCCMonthlyPlusOne.Visible = false;
        pnlMailMonthly.Visible = false;
        pnlCCOne.Visible = false;
        pnlCCOneSurgery.Visible = false;
        pnlMailOne.Visible = false;
        pnlMailOneSurgery.Visible = false;
        pnlBrochure.Visible = false;
        pnlTShirt.Visible = false;
        pMailMonthlyPlusOne.Visible = false;

        //determines number of full surgeries
        int ikids = Convert.ToInt32(Math.Floor(Convert.ToDouble(lblTotalOneTime.Text)));
        ikids = ikids / 240;
        string skids;
        if(ikids > 1)
        {
            skids = " complete surgeries for " + ikids.ToString() + " children. Your donation will truly transform these children's lives ";
        }
        else
        {
            skids = " a complete surgery for " + ikids.ToString() + " child. Your donation will truly transform this child's life ";
        }

        switch (ddlPaymentType.SelectedIndex)
        {
            case 1: //CC
                //if cc declined
                if (lblReturnValue.Text.IndexOf("OK") <= 0)
                {
                    //if monthly or both
                    if (Convert.ToDouble(lblMonthlyDonation.Text) > 0.0)    //if monthly
                    {
                        if (cbOneTimeToo.Checked && Convert.ToDouble(tbOpenOneTime.Text) > 0.0)   //if both
                        {
                            ((DataAccess)Session["App"]).PutCallData("UpFrontAmount", lblTotalOneTime.Text);
                            ((DataAccess)Session["App"]).PutCallData("RecurringAmount", lblMonthlyDonation.Text);
                            ((DataAccess)Session["App"]).PutCallData("RecurringPaymentDay", ddlPmtDay.SelectedValue);

                            //This is done b/c we treat the motivation code for both as though it
                            if (Convert.ToDouble(lblTotalOneTime.Text) >= 240.0)
                            {
                                ((DataAccess)Session["App"]).PutCallData("MotivationCode", "K8");   //one-time mail-in over 240
                            }
                            else
                            {
                                ((DataAccess)Session["App"]).PutCallData("MotivationCode", "J7");   //one-time mail-in under 240
                            }
                            if (dispo)
                            {
                                ((DataAccess)Session["App"]).PutCallData("Webusercode", "13");
                            }
                        }
                        //if monthly
                        else
                        {
                            ((DataAccess)Session["App"]).PutCallData("MotivationCode", "F3");

                            ((DataAccess)Session["App"]).PutCallData("UpFrontAmount", lblMonthlyDonation.Text);
                            ((DataAccess)Session["App"]).PutCallData("RecurringAmount", lblMonthlyDonation.Text);
                            ((DataAccess)Session["App"]).PutCallData("RecurringPaymentDay", ddlPmtDay.SelectedValue);

                            if (dispo)
                            {
                                ((DataAccess)Session["App"]).PutCallData("Webusercode", "12");
                            }
                        }
                            pnlBadCCMonthly.Visible = true;

                    }
                    else //(Convert.ToDouble(tbOpenOneTime.Text) > 0.0)    
                    {
                        //one-time
                        
                        ((DataAccess)Session["App"]).PutCallData("UpFrontAmount", lblTotalOneTime.Text);
                        ((DataAccess)Session["App"]).PutCallData("RecurringAmount", "0.0");
                        ((DataAccess)Session["App"]).PutCallData("RecurringPaymentDay", "0");

                        if (dispo)
                        {
                            ((DataAccess)Session["App"]).PutCallData("Webusercode", "13");
                        }

                        if (Convert.ToDouble(lblTotalOneTime.Text) >= 240.0)
                        {
                            ((DataAccess)Session["App"]).PutCallData("MotivationCode", "K8");   //one-time mail-in over 240
                        }
                        else
                        {
                            ((DataAccess)Session["App"]).PutCallData("MotivationCode", "J7");   //one-time mail-in under 240
                        }

                        pnlBadCCOneTime.Visible = true;
                    }
                    
                }
                //if both monthly and one-time cc payment
                else if (Convert.ToDouble(tbOpenOneTime.Text) > 0.0 && Convert.ToDouble(lblMonthlyDonation.Text) > 0.0)
                {
                    pnlCCMonthlyPlusOne.Visible = true;
                    lblCCMonthlyPlusOne1.Text = lblTotalOneTime.Text;
                    lblCCMonthlyPlusOne2.Text = lblMonthlyDonation.Text;
                    lblCCMonthlyPlusOneDate.Text = ddlPmtDay.SelectedItem.Text;
                    ((DataAccess)Session["App"]).PutCallData("UpFrontAmount", lblAuthAmt.Text);
                    ((DataAccess)Session["App"]).PutCallData("RecurringAmount", lblMonthlyDonation.Text);
                    ((DataAccess)Session["App"]).PutCallData("RecurringPaymentDay", ddlPmtDay.SelectedValue);

                    if (Convert.ToDouble(lblTotalOneTime.Text) >= 240.0)
                    {
                        ((DataAccess)Session["App"]).PutCallData("MotivationCode", "H6");   //one-time CC over 240

                        if (dispo)
                        {
                            ((DataAccess)Session["App"]).PutCallData("Webusercode", "01");
                        }
                    }
                    else
                    {
                        ((DataAccess)Session["App"]).PutCallData("MotivationCode", "G5");   //one-time CC under 240

                        if (dispo)
                        {
                            ((DataAccess)Session["App"]).PutCallData("Webusercode", "02");
                        }
                    }
                }
                //if just one-time payment
                else if (Convert.ToDouble(tbOpenOneTime.Text) > 0.0 && Convert.ToDouble(lblMonthlyDonation.Text) <= 0.0)
                {
                    ((DataAccess)Session["App"]).PutCallData("UpFrontAmount", lblAuthAmt.Text);
                    ((DataAccess)Session["App"]).PutCallData("RecurringAmount", "0.0");
                    ((DataAccess)Session["App"]).PutCallData("RecurringPaymentDay", "0");
                    //if one-time total provides for at least 1 surgery
                    if (Convert.ToDouble(lblTotalOneTime.Text) >= 240.0)
                    {
                        pnlCCOneSurgery.Visible = true;
                        lblCCOneSurgery0.Text = lblTotalOneTime.Text;
                        lblCCOneSurgeryChildren.Text = skids;
                        ((DataAccess)Session["App"]).PutCallData("MotivationCode", "H6");   //one-time CC over 240

                        if (dispo)
                        {
                            ((DataAccess)Session["App"]).PutCallData("Webusercode", "01");
                        }
                        
                    }
                    else
                    {
                        pnlCCOne.Visible = true;
                        lblCCOne0.Text = lblTotalOneTime.Text;
                        ((DataAccess)Session["App"]).PutCallData("MotivationCode", "G5");   //one-time CC under 240

                        if (dispo)
                        {
                            ((DataAccess)Session["App"]).PutCallData("Webusercode", "02");
                        }
                    }
                }
                //if cc payment and monthly
                else
                {
                    ((DataAccess)Session["App"]).PutCallData("UpFrontAmount", lblAuthAmt.Text);
                    ((DataAccess)Session["App"]).PutCallData("RecurringAmount", lblMonthlyDonation.Text);
                    ((DataAccess)Session["App"]).PutCallData("RecurringPaymentDay", ddlPmtDay.SelectedValue);
                    pnlCCMonthly.Visible = true;
                    lblCCmonthly0.Text = lblMonthlyDonation.Text;
                    lblCCmonthly1.Text = lblMonthlyDonation.Text;
                    lblCCmonthly2.Text = lblMonthlyDonation.Text;
                    lblCCMonthlyDate.Text = ddlPmtDay.SelectedItem.Text;
                    ((DataAccess)Session["App"]).PutCallData("MotivationCode", "D1");   //monthly partner CC

                    if (dispo)
                    {
                        ((DataAccess)Session["App"]).PutCallData("Webusercode", "03");
                    }
                }
                //if call qualifies for t-shirt
                if ((Convert.ToDouble(lblTotalOneTime.Text) >= 240.0 || Convert.ToDouble(lblMonthlyDonation.Text) >= 18.0) && lblReturnValue.Text.IndexOf("OK") > 0)
                {
                    pnlTShirt.Visible = true;
                }
                break;
            //case 2: //EFT

            //    break;
            case 2: //Mail-in
                //if mail in for single and recurring pmt
                if (Convert.ToDouble(tbOpenOneTime.Text) > 0.0 && Convert.ToDouble(lblMonthlyDonation.Text) > 0.0)
                {
                    ((DataAccess)Session["App"]).PutCallData("UpFrontAmount", lblTotalOneTime.Text);
                    ((DataAccess)Session["App"]).PutCallData("RecurringAmount", lblMonthlyDonation.Text);
                    ((DataAccess)Session["App"]).PutCallData("RecurringPaymentDay", ddlPmtDay.SelectedValue);
                    pnlMailOne.Visible = true;
                    pMailMonthlyPlusOne.Visible = true;
                    lblMailOne0.Text = lblTotalOneTime.Text; 
                    if (Convert.ToDouble(lblTotalOneTime.Text) >= 240.0)
                    {
                        ((DataAccess)Session["App"]).PutCallData("MotivationCode", "K8");   //one-time mail-in over 240

                        if (dispo)
                        {
                            ((DataAccess)Session["App"]).PutCallData("Webusercode", "06");
                        }
                    }
                    else
                    {
                        ((DataAccess)Session["App"]).PutCallData("MotivationCode", "J7");   //one-time mail-in under 240

                        if (dispo)
                        {
                            ((DataAccess)Session["App"]).PutCallData("Webusercode", "07");
                        }
                    }
                }
                //if just one-time payent
                else if (Convert.ToDouble(tbOpenOneTime.Text) > 0.0 && Convert.ToDouble(lblMonthlyDonation.Text) <= 0.0)
                {
                    ((DataAccess)Session["App"]).PutCallData("UpFrontAmount", lblTotalOneTime.Text);
                    ((DataAccess)Session["App"]).PutCallData("RecurringAmount", "0.0");
                    ((DataAccess)Session["App"]).PutCallData("RecurringPaymentDay", "0");
                    //if one-time total provides for at least 1 surgery
                    if (Convert.ToDouble(lblTotalOneTime.Text) >= 240.0)
                    {
                        pnlMailOneSurgery.Visible = true;
                        lblMailOneSurgery0.Text = lblTotalOneTime.Text;
                        lblMailOneSurgeryChildren.Text = skids;
                        ((DataAccess)Session["App"]).PutCallData("MotivationCode", "K8");   //one-time mail-in over 240

                        if (dispo)
                        {
                            ((DataAccess)Session["App"]).PutCallData("Webusercode", "06");
                        }
                    }
                    else
                    {
                       pnlMailOne.Visible = true;
                       lblMailOne0.Text = lblTotalOneTime.Text;
                       ((DataAccess)Session["App"]).PutCallData("MotivationCode", "J7");   //one-time mail-in under 240

                       if (dispo)
                       {
                           ((DataAccess)Session["App"]).PutCallData("Webusercode", "07");
                       }
                    }
                }
                //if Mail payment and monthly
                else
                {
                    ((DataAccess)Session["App"]).PutCallData("UpFrontAmount", lblMonthlyDonation.Text);
                    ((DataAccess)Session["App"]).PutCallData("RecurringAmount", lblMonthlyDonation.Text);
                    ((DataAccess)Session["App"]).PutCallData("RecurringPaymentDay", ddlPmtDay.SelectedValue);
                    ((DataAccess)Session["App"]).PutCallData("MotivationCode", "F3");   //recurring mail-in 

                    if (dispo)
                    {
                        ((DataAccess)Session["App"]).PutCallData("Webusercode", "08");
                    }
                    pnlMailMonthly.Visible = true;
                    lblMailMonthly0.Text = lblMonthlyDonation.Text;
                }
                break;
            case 3: //Brochure
                pnlBrochure.Visible = true;
                    ((DataAccess)Session["App"]).PutCallData("UpFrontAmount", "0.0");
                    ((DataAccess)Session["App"]).PutCallData("RecurringAmount", "0.0");
                    ((DataAccess)Session["App"]).PutCallData("RecurringPaymentDay", "0");
                    ((DataAccess)Session["App"]).PutCallData("MotivationCode", "F4");   //recurring mail-in under 240

                    if (dispo)
                    {
                        ((DataAccess)Session["App"]).PutCallData("Webusercode", "10");
                    }
                break;
        }
        ((DataAccess)Session["App"]).CommitCallData();
    }
    protected void btnWhyCall_Click(object sender, EventArgs e)
    {
        pnlFAQ.Visible = false;
        pnlWizard.Visible = false;
        pnlNotes.Visible = false;
        btnWhyCall.Text = "Go To Reasons for Calling";
        btnNotes.Text = "Go To Notes";
        btnFAQ.Text = "View FAQ";

        if (pnlWhyCall.Visible)
        {
            pnlWhyCall.Visible = false;
            pnlWizard.Visible = true;
        }
        else
        {
            pnlWhyCall.Visible = true;
            btnWhyCall.Text = "Return to Script";
        }
        
    }
    protected void btnNotes_Click(object sender, EventArgs e)
    {
        //SendEmail();
        pnlFAQ.Visible = false;
        pnlWizard.Visible = false;
        pnlWhyCall.Visible = false;
        btnNotes.Text = "Go To Notes";
        btnFAQ.Text = "View FAQ";
        btnWhyCall.Text = "Go To Reasons for Calling";

        if (pnlNotes.Visible)
        {
            pnlNotes.Visible = false;
            pnlWizard.Visible = true;
        }
        else
        {
            pnlNotes.Visible = true;
            btnNotes.Text = "Return to Script";
        }
    }
    protected void btnFAQ_Click(object sender, EventArgs e)
    {
        btnFAQ.Text = "View FAQ";
        btnNotes.Text = "Go To Notes";
        btnWhyCall.Text = "Go To Reasons for Calling";
        pnlWizard.Visible = false;
        pnlNotes.Visible = false;
        pnlWhyCall.Visible = false;

        if (pnlFAQ.Visible)
        {
            pnlFAQ.Visible = false;
            pnlWizard.Visible = true;
        }
        else
        {
            pnlFAQ.Visible = true;
            btnFAQ.Text = "Return to Script";
        }
    }

    protected void prepopulateFields()
    {
        bool bHasShipInfo = false;
        bHasShipInfo = !(string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("ShippingAddress")) &&
                        string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("ShippingAddress2")) &&
                        string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("ShippingZip")));

        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("FirstName")))
        {
            tbFirstName.Text = ((DataAccess)Session["App"]).GetCallData("FirstName");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("LastName")))
        {
            tbLastName.Text = ((DataAccess)Session["App"]).GetCallData("LastName");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("Address")))
        {
            tbAddr.Text = ((DataAccess)Session["App"]).GetCallData("Address");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("Address2")))
        {
            tbAddr2.Text = ((DataAccess)Session["App"]).GetCallData("Address2");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("Zip")))
        {
            tbZip.Text = ((DataAccess)Session["App"]).GetCallData("Zip");
            btnSearchZip_Click(null, null); //run logic for getting city info from zip
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("Phone")))
        {
            tbPhone.Text = ((DataAccess)Session["App"]).GetCallData("Phone");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("Email")))
        {
            tbEmail.Text = ((DataAccess)Session["App"]).GetCallData("Email");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("ShippingAddress")))
        {
            tbShipAddr.Text = ((DataAccess)Session["App"]).GetCallData("ShippingAddress");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("ShippingAddress2")))
        {
            tbShipaddr2.Text = ((DataAccess)Session["App"]).GetCallData("ShippingAddress2");
        }
        if (!string.IsNullOrEmpty(((DataAccess)Session["App"]).GetCallData("ShippingZip")))
        {
            tbShipZip.Text = ((DataAccess)Session["App"]).GetCallData("ShippingZip");
            btnShipSearchZip_Click(null, null);
        }
        if (bHasShipInfo)
        {
            cbShipping.Checked = true;
            cbShipping_CheckedChanged(null, null);
        }
        
    }
    private void ProcessCard()
    {

        //string agentCode = "TEST88";
        //string password = "TEST88";
        //string customerIPAddress = "10.22.2.11";
        //string invoiceNum = "12345";
        //string ccNum = "4111111111111111";
        //string ccExp = "03/13";
        //string cvv2 = "1234";
        //string mop = "VISA";
        //string firstName = "";
        //string lastName = "";
        //string address = "11";
        //string city = "cd";
        //string state = "ee";
        //string zipCode = "ww";
        //string total = "10";
        //string comment = "luke test ProcessCreditCardV1";

        string agentCode = "3LNK94";
        string password = "GBJ4678";
        string customerIPAddress = "";
        string invoiceNum = ((DataAccess)Session["App"]).GetCallData("enterpriselistid").ToString();
        string ccNum = tbCCNumber.Text;
        string ccExp = tbExpDate.Text.Substring(0, 2) + "/" + tbExpDate.Text.Substring(2, 2);
        string cvv2 = tbCCV.Text;
        string mop;
        switch (ddlCardType.SelectedValue)
        {
            case "V":
                mop = "VISA";
                break;
            case "A":
                mop = "AMX";
                break;
            case "D":
                mop = "DSC";
                break;
            case "M":
                mop = "MC";
                break;
            default:
                mop = "VISA";
                break;
        }

        string firstName = tbFirstName.Text;
        string lastName = tbLastName.Text;
        string address = tbAddr.Text + " " + tbAddr2.Text;
        string city = ddlCity.SelectedItem.Text;
        string state = ddlState.SelectedItem.Text;
        string zipCode = tbZip.Text;
        string total = lblAuthAmt.Text;
        string comment = "";

        try
        {
            com.iatspayments.www.ProcessLink pl = new com.iatspayments.www.ProcessLink();

            System.Xml.XmlNode result = pl.ProcessCreditCard(agentCode, password, customerIPAddress, invoiceNum, ccNum, ccExp, cvv2, mop, firstName, lastName, address, city, state, zipCode, total, comment);
            if (result.SelectSingleNode("//STATUS").InnerText.ToUpper() != "SUCCESS")
            {
                ((DataAccess)Session["App"]).PutCallData("IATSError", result.SelectSingleNode("//ERRORS").InnerText);   //put connection errors in the db.
            }
            else
            {
                lblReturnValue.Text = result.SelectSingleNode("//AUTHORIZATIONRESULT").InnerText;
                lblTransactionID.Text = result.SelectSingleNode("//TRANSACTIONID").InnerText;

                if (lblReturnValue.Text.IndexOf("OK") > 0)
                {
                    lblAuthError.Text = "Successfully Authorized";
                    btnAuthCard.Enabled = false;
                }
                else
                {
                    lblAuthError.Text = "Card Failed";
                    pnlCCReAuth.Visible = true;
                }
            }

        }
        catch (Exception ex)
        {
            lblAuthError.Text = "There was an issue with the webservice. Please put this in the notes section and hit next";
            ((DataAccess)Session["App"]).PutCallData("IATSError", ex.ToString());   //put exceptions in the db.
        }
        ((DataAccess)Session["App"]).PutCallData("AuthCode", lblReturnValue.Text);  //put actual authorization result in the database
        ((DataAccess)Session["App"]).PutCallData("TransactionID", lblTransactionID.Text);   //put transaction id in the database
        ((DataAccess)Session["App"]).CommitCallData();
    }


    protected void btnAuthCard_Click(object sender, EventArgs e)
    {
        if (validateCustomer() && validatePayment())    //make sure we have valid customer and card data
        {
            lblAuthError.Text = "";
            ProcessCard();

        }
        else
        {
            lblAuthError.Text = "Missing data. Please verify card info at the right";
        }
    }
    protected void tbNotes_TextChanged(object sender, EventArgs e)
    {
        if(!string.IsNullOrEmpty(tbNotes.Text))
        {
            ((DataAccess)Session["App"]).PutCallData("Notes",tbNotes.Text);
        }
    }
    protected void SendEmail()
    {
        if (submitOptionalData() && !string.IsNullOrEmpty(tbEmail.Text))
        {
            EmailSet("ThankYou@OperationSmile.org", "ThankYou", "mail.focusservices.com");
            string[] EmailTo = new string[1];
            //string[] EmailAttachments = new string[1];
            EmailTo[0] = ((DataAccess)Session["App"]).GetCallData("Email");
            
            string EmailSubject = "";// = "City Squares Presentation";
            string EmailBody = "";// = "Thank you for taking a few moments to learn about City Squares free tial offer.  Attached is our presentation for you to review.";
            switch(((DataAccess)Session["App"]).GetCallData("Webusercode").ToString())
            {
                case "02":
                    EmailSubject = "Thank you for your generous gift of new smiles";
                    using (System.IO.StreamReader reader = System.IO.File.OpenText(Server.MapPath("Emails/OneTimeCC.html")))
                    {
                        EmailBody = reader.ReadToEnd();
                        EmailBody = EmailBody.Replace("CustName", ddlTitle.SelectedItem.Text + " " + tbLastName.Text).Replace("ProdAmount", ((DataAccess)Session["App"]).GetCallData("UpFrontAmount").ToString());
                    }
                    break;

                case "06":
                    EmailSubject = "Thank you for your generous pledge";
                    using (System.IO.StreamReader reader = System.IO.File.OpenText(Server.MapPath("Emails/OneTimeSurgeryPledge.html")))
                    {
                        EmailBody = reader.ReadToEnd();
                        EmailBody = EmailBody.Replace("CustName", ddlTitle.SelectedItem.Text + " " + tbLastName.Text).Replace("ProdAmount", ((DataAccess)Session["App"]).GetCallData("UpFrontAmount").ToString());
                    }
                    break;

                case "07":
                case "13":
                    EmailSubject = "Thank you for your generous pledge";
                    using (System.IO.StreamReader reader = System.IO.File.OpenText(Server.MapPath("Emails/OneTimePledge.html")))
                    {
                        EmailBody = reader.ReadToEnd();
                        EmailBody = EmailBody.Replace("CustName", ddlTitle.SelectedItem.Text + " " + tbLastName.Text).Replace("ProdAmount", ((DataAccess)Session["App"]).GetCallData("UpFrontAmount").ToString());
                    }
                    break;

                case "10":
                    EmailSubject = "Thank you for your interest";
                    using (System.IO.StreamReader reader = System.IO.File.OpenText(Server.MapPath("Emails/Brochure.html")))
                    {
                        EmailBody = reader.ReadToEnd();
                        EmailBody = EmailBody.Replace("CustName", ddlTitle.SelectedItem.Text + " " + tbLastName.Text);
                    }
                    break;

                case "08":
                case "12":
                    EmailSubject = "Thank you for your Smile Partner pledge";
                    using (System.IO.StreamReader reader = System.IO.File.OpenText(Server.MapPath("Emails/RecurringPledge.html")))
                    {
                        EmailBody = reader.ReadToEnd();
                        EmailBody = EmailBody.Replace("CustName", ddlTitle.SelectedItem.Text + " " + tbLastName.Text).Replace("ProdAmount", ((DataAccess)Session["App"]).GetCallData("UpFrontAmount").ToString());
                    }
                    break;

                case "01":
                    EmailSubject = "Thank you for your generous gift of new smiles";
                    using (System.IO.StreamReader reader = System.IO.File.OpenText(Server.MapPath("Emails/OneTimeSurgeryCC.html")))
                    {
                        EmailBody = reader.ReadToEnd();
                        EmailBody = EmailBody.Replace("CustName", ddlTitle.SelectedItem.Text + " " + tbLastName.Text).Replace("ProdAmount", ((DataAccess)Session["App"]).GetCallData("UpFrontAmount").ToString());
                    }
                    break;
                    
                case "03":
                    EmailSubject = "Thank you for becoming a Smile Partner";
                    using (System.IO.StreamReader reader = System.IO.File.OpenText(Server.MapPath("Emails/MonthlyCC.html")))
                    {
                        EmailBody = reader.ReadToEnd();
                        EmailBody = EmailBody.Replace("CustName", ddlTitle.SelectedItem.Text + " " + tbLastName.Text).Replace("ProdAmount", ((DataAccess)Session["App"]).GetCallData("UpFrontAmount").ToString());
                    }
                    break;
            }

            if (EmailSend(EmailTo, null, EmailSubject, EmailBody, true, null))
            {
                lblError.Text = "Email Successfully Sent";
            }
            else
            {
                EmailSet("jared.ballingham@focusservices.com", "EmailError", "mail.focusservices.com");
                EmailTo[0] = "jared.ballingham@focusservices.com";

                EmailSubject = "Auto e-mail for list ID" + Session["listid"] + "failed to send";// = "City Squares Presentation";
                EmailBody = "Please review and test.";// = "Thank you for taking a few moments to learn about City Squares free tial offer.  Attached is our presentation for you to review.";
                EmailSend(EmailTo, null, EmailSubject, EmailBody, false);
            }
        }
        
    }
    #region Email Procedures
    public void EmailSet(string FromEmail, string FromName, string EmailServer, string LoginName, string LoginPassword)
    {
        _EmailServer = EmailServer;
        _LoginName = LoginName;
        _LoginPassword = LoginPassword;
        _FromEmail = FromEmail;
        _FromName = FromName;

    }

    //This is an overload in case the username and password are not requried
    public void EmailSet(string FromEmail, string FromName, string EmailServer)
    {
        _EmailServer = EmailServer;
        _FromEmail = FromEmail;
        _FromName = FromName;
    }

    public bool EmailSend(string[] _ToEmail, string[] _CCEmail, string _Subject, string _EmailBody, bool _IsBodyHtml, string[] _Attachments)
    {

        try
        {
            // setup email header
            System.Net.Mail.MailMessage _MailMessage = new System.Net.Mail.MailMessage();

            // Set the message sender
            // sets the from address for this e-mail message.
            _MailMessage.From = new System.Net.Mail.MailAddress(_FromEmail, _FromName);
            // Sets the address collection that contains the recipients of this e-mail message.
            int counter = 0;
            foreach (string Recipients in _ToEmail)
            {
                _MailMessage.To.Add(new System.Net.Mail.MailAddress(_ToEmail[counter]));
                counter++;
            }

            counter = 0;
            if (_CCEmail != null && _CCEmail.Length > 0)
            {
                foreach (string CCRecipients in _CCEmail)
                {
                    _MailMessage.CC.Add(new System.Net.Mail.MailAddress(_CCEmail[counter]));
                    counter++;
                }
            }

            // sets the message subject.
            _MailMessage.Subject = _Subject;
            // sets the message body.
            _MailMessage.Body = _EmailBody;
            // sets a value indicating whether the mail message body is in Html.
            // if this is false then ContentType of the Body content is "text/plain".
            _MailMessage.IsBodyHtml = _IsBodyHtml;

            // add all the file attachments if we have any
            if (_Attachments != null && _Attachments.Length > 0)
                foreach (string _Attachment in _Attachments)
                    _MailMessage.Attachments.Add(new System.Net.Mail.Attachment(_Attachment));

            // SmtpClient Class Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
            System.Net.Mail.SmtpClient _SmtpClient = new System.Net.Mail.SmtpClient(_EmailServer);

            //Specifies how email messages are delivered. Here Email is sent through the network to an SMTP server.
            _SmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

            // Some SMTP server will require that you first authenticate against the server.
            // Provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.
            System.Net.NetworkCredential _NetworkCredential = new System.Net.NetworkCredential(_LoginName, _LoginPassword);
            _SmtpClient.UseDefaultCredentials = false;
            _SmtpClient.Credentials = _NetworkCredential;

            //Let's send it
            _SmtpClient.Send(_MailMessage);

            // Do cleanup
            _MailMessage.Dispose();
            _SmtpClient = null;
        }
        catch
        {
            return false;
        }
        return true;
    }

    public bool EmailSend(string[] _ToEmail, string[] _CCEmail, string _Subject, string _EmailBody, bool _IsBodyHtml)
    {
        try
        {
            // setup email header
            System.Net.Mail.MailMessage _MailMessage = new System.Net.Mail.MailMessage();

            // Set the message sender
            // sets the from address for this e-mail message.
            _MailMessage.From = new System.Net.Mail.MailAddress(_FromEmail, _FromName);
            // Sets the address collection that contains the recipients of this e-mail message.
            int counter = 0;
            foreach (string Recipients in _ToEmail)
            {
                _MailMessage.To.Add(new System.Net.Mail.MailAddress(_ToEmail[counter]));
                counter++;
            }

            counter = 0;
            if (_CCEmail != null && _CCEmail.Length > 0)
            {
                foreach (string CCRecipients in _CCEmail)
                {
                    _MailMessage.CC.Add(new System.Net.Mail.MailAddress(_CCEmail[counter]));
                    counter++;
                }
            }

            // sets the message subject.
            _MailMessage.Subject = _Subject;
            // sets the message body.
            _MailMessage.Body = _EmailBody;
            // sets a value indicating whether the mail message body is in Html.
            // if this is false then ContentType of the Body content is "text/plain".
            _MailMessage.IsBodyHtml = _IsBodyHtml;


            // SmtpClient Class Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
            System.Net.Mail.SmtpClient _SmtpClient = new System.Net.Mail.SmtpClient(_EmailServer);

            //Specifies how email messages are delivered. Here Email is sent through the network to an SMTP server.
            _SmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

            // Some SMTP server will require that you first authenticate against the server.
            // Provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.
            System.Net.NetworkCredential _NetworkCredential = new System.Net.NetworkCredential(_LoginName, _LoginPassword);
            _SmtpClient.UseDefaultCredentials = false;
            _SmtpClient.Credentials = _NetworkCredential;

            //Let's send it
            _SmtpClient.Send(_MailMessage);

            // Do cleanup
            _MailMessage.Dispose();
            _SmtpClient = null;
        }
        catch
        {
            return false;
        }
        return true;
    }

    #endregion Email Procedures

    //protected void SendEmail(string s)
    //{
    //        EmailSet("ThankYou@OperationSmile.org", "ThankYou", "mail.focusservices.com");
    //        string[] EmailTo = new string[1];
    //        //string[] EmailAttachments = new string[1];
    //        EmailTo[0] = "jared.ballingham@focusservices.com";//((DataAccess)Session["App"]).GetCallData("Email");

    //        string EmailSubject = "";// = "City Squares Presentation";
    //        string EmailBody = "";// = "Thank you for taking a few moments to learn about City Squares free tial offer.  Attached is our presentation for you to review.";
    //        EmailSubject = "Thank you for your generous gift of new smiles";
    //        using (System.IO.StreamReader reader = System.IO.File.OpenText(Server.MapPath("Emails/OneTimeCC.html")))
    //        {
    //            EmailBody = reader.ReadToEnd();
    //            EmailBody = EmailBody.Replace("CustName", ddlTitle.SelectedItem.Text + " " + tbLastName.Text).Replace("ProdAmount", ((DataAccess)Session["App"]).GetCallData("UpFrontAmount").ToString());
    //        }
    //        //System.IO.File test = new System.IO.File();
    //        //EmailBody = test ("~/sharedpool/OperationSmile/Emails/OneTimeCC.html").ReadToEnd();
    //        //}

    //        if (EmailSend(EmailTo, null, EmailSubject, EmailBody, true, null))
    //            lblError.Text = "Email Successfully Sent";
    //        else
    //            lblError.Text = "Email Failed to Send";

    //}

    protected void ddlWhyCall_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlWhyCall.SelectedItem.Text == "Other")
        {
            pWhyOther.Visible = true;
        }
        else
        {
            pWhyOther.Visible = false;
        }

        ddlSurvey.SelectedIndex = ddlWhyCall.SelectedIndex; //set survey result to whatever they said.
        ddlSurvey_SelectedIndexChanged(null, null); //this will show or hide psurvey other based on selection
    }
    protected void tbWhyOther_TextChanged(object sender, EventArgs e)
    {
        tbSurveyOther.Text = tbWhyOther.Text;
    }
    protected void ddlSurvey_SelectedIndexChanged(object sender, EventArgs e)
    {
        Page.SetFocus(ddlSurvey);
        if (ddlSurvey.SelectedItem.Text == "Other")
        {
            pSurveyOther.Visible = true;
        }
        else
        {
            pSurveyOther.Visible = false;
        }
    }
}
